package cn.itcast.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.aspectj.util.FileUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;

public class PromotionAction extends BaseAction<Promotion> {
	private File titleImgFile;
	private String imgFileFileName;

	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	// 保存活动的方法
	@Resource
	private PromotionService service;

	@Action(value = "promotion_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/take_delivery/promotion_add.html") })
	public String promotionAdd() throws IOException {
		// 图片处理
		// 随机文件名
		String fileName = UUID.randomUUID().toString();
		// 扩展名
		String ext = FilenameUtils.getExtension(imgFileFileName);
		// 拼接成完整的文件名
		fileName = fileName + "." + ext;
		// 保存文件
		FileUtil.copyFile(titleImgFile, new File("F:/temp/upload/" + fileName));
		// 图片服务器地址
		String serverUrl = "http://localhost:8080/upload/";
		model.setTitleImg(serverUrl + fileName);
		service.save(model);
		return SUCCESS;
	}

	// 简单的无条件分页查询
	@Action(value = "promotion_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		// 创建分页查询参数
		Pageable pageable = new PageRequest(page - 1, rows);
		Page<Promotion> pageData = service.findPage(pageable);
		// 将数据压入值栈
		pushPageDataToValueStack(pageData);
		return SUCCESS;
	}
}
